<template>
  <div class="login-page">
    <div class="login-container">
      <h1>登录医疗众包平台</h1>
      
      <div v-if="error" class="error-message">
        {{ error }}
      </div>
      
      <form @submit.prevent="login">
        <div class="form-group">
          <label for="username">用户名</label>
          <input 
            type="text" 
            id="username" 
            v-model="credentials.username" 
            required
            placeholder="请输入用户名"
          >
        </div>
        
        <div class="form-group">
          <label for="password">密码</label>
          <input 
            type="password" 
            id="password" 
            v-model="credentials.password" 
            required
            placeholder="请输入密码"
          >
        </div>
        
        <div class="form-actions">
          <button type="submit" class="btn btn-primary" :disabled="loading">
            {{ loading ? '登录中...' : '登录' }}
          </button>
          <router-link to="/register" class="register-link">
            还没有账号？立即注册
          </router-link>
        </div>
      </form>
      
      <!-- 添加调试面板 -->
      <div v-if="isLoggedIn" class="debug-panel">
        <h3>当前用户信息</h3>
        <pre>{{ JSON.stringify(currentUser, null, 2) }}</pre>
        
        <div class="form-group">
          <label>设置用户角色</label>
          <div class="role-buttons">
            <button @click="setUserRole(1)" class="btn btn-small">设为研究者(1)</button>
            <button @click="setUserRole(2)" class="btn btn-small">设为参与者(2)</button>
          </div>
        </div>
        
        <div class="form-group">
          <button @click="testCreateProject" class="btn btn-small btn-primary">测试访问创建项目</button>
        </div>
      </div>
      
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      credentials: {
        username: '',
        password: ''
      },
      loading: false,
      error: null
    }
  },
  computed: {
    isLoggedIn() {
      return this.$store.getters['auth/isAuthenticated'];
    },
    currentUser() {
      return this.$store.getters['auth/currentUser'];
    }
  },
  methods: {
    async login() {
      this.loading = true
      this.error = null
      
      console.log('开始登录流程，提交凭据:', {
        username: this.credentials.username,
        password: '******'
      });
      
      try {
        // 调用Vuex中的auth模块的login方法
        const response = await this.$store.dispatch('auth/login', this.credentials)
        
        // 调试用户信息
        console.log('登录成功，返回数据:', response?.data)
        
        // 获取用户信息并打印
        console.log('从getter获取的用户:', this.currentUser)
        
        // 检查用户角色
        const isResearcher = this.$store.getters['auth/isResearcher']
        console.log('用户是否为研究者:', isResearcher)
        
        // 如果用户数据不完整，尝试再次获取
        if (!this.currentUser || !this.currentUser.role) {
          console.log('用户数据不完整，尝试获取完整信息');
          try {
            // 尝试获取完整用户信息
            await this.$store.dispatch('auth/fetchUser');
            console.log('获取完整用户信息后:', this.$store.getters['auth/currentUser']);
          } catch (fetchError) {
            console.error('获取完整用户信息失败:', fetchError);
            // 继续执行，不影响登录流程
          }
        }
        
        // 保存重定向目标
        const redirect = this.$route.query.redirect;
        const targetRoute = redirect === 'create-project' ? '/create-project' : '/';
        
        // 登录成功后直接跳转，不显示alert
        console.log('登录成功，正在跳转到:', targetRoute);
        
        // 直接使用router导航到目标页面，避免刷新页面
        this.$router.push(targetRoute);
      } catch (error) {
        console.error('登录失败:', error.response?.data || error);
        this.error = error.response?.data?.message || '登录失败，请检查用户名和密码'
      } finally {
        this.loading = false
      }
    },
    setUserRole(role) {
      // 设置用户角色
      console.log('设置用户角色:', role);
      this.$store.dispatch('auth/setUserRole', role)
        .then(result => {
          console.log('角色设置结果:', result);
          // 刷新用户信息
          this.currentUser = this.$store.getters['auth/currentUser'];
          
          // 显示成功消息
          alert(`已将用户角色设置为: ${role === 1 ? '研究者' : '参与者'}`);
        })
        .catch(error => {
          console.error('设置角色失败:', error);
          alert('设置角色失败');
        });
    },
    testCreateProject() {
      // 测试访问创建项目页面
      console.log('测试访问创建项目');
      // 先检查角色
      const isResearcher = this.$store.getters['auth/isResearcher'];
      console.log('当前用户是否为研究者:', isResearcher);
      
      if (isResearcher) {
        this.$router.push('/create-project');
      } else {
        alert('您不是研究者，无法访问创建项目页面。请先设置角色为研究者(1)。');
      }
    }
  }
}
</script>

<style scoped>
.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
}

.login-container {
  width: 100%;
  max-width: 400px;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

h1 {
  text-align: center;
  margin-bottom: 24px;
  color: #2c3e50;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #2c3e50;
}

input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.form-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.btn {
  width: 100%;
  padding: 12px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  margin-bottom: 12px;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-primary:hover {
  background-color: #2980b9;
}

.btn:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
}

.register-link {
  color: #3498db;
  text-decoration: none;
  font-size: 14px;
}

.register-link:hover {
  text-decoration: underline;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.debug-panel {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.role-buttons {
  display: flex;
  justify-content: center;
  margin-bottom: 12px;
}

.btn-small {
  padding: 8px 16px;
  margin: 0 8px;
}
</style> 